package com.zym.init.core.validator;

import com.zym.init.core.annotation.EnumRange;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 枚举类范围校验器
 */
public class EnumRangeValidator implements ConstraintValidator<EnumRange, Object> {

    private Class<? extends Enum<?>> enumClass;
    private String enumValidMethod;

    @Override
    public void initialize(EnumRange enumRange) {
        enumClass = enumRange.enumClass();
        enumValidMethod = enumRange.enumValidMethod();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        }

        if (enumClass == null || enumValidMethod == null) {
            return true;
        }

        Class<?> valueClass = value.getClass();

        try {
            // 反射获取方法
            Method method = enumClass.getMethod(enumValidMethod, valueClass);
            // 校验 enumValidMethod 是否为 boolean类型方法
            if (!Boolean.TYPE.equals(method.getReturnType()) && !Boolean.class.equals(method.getReturnType())) {
                throw new RuntimeException(enumValidMethod + " method return is not boolean type in the " + enumClass + " class");
            }
            // 校验 enumValidMethod 是否为 静态类型方法
            if (!Modifier.isStatic(method.getModifiers())) {
                throw new RuntimeException(enumValidMethod + " method is not static method in the " + enumClass + " class");
            }
            // 反射调用该方法
            Boolean result = (Boolean) method.invoke(null, value);

            return result != null && result;
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException | SecurityException e) {
            throw new RuntimeException("This " + enumValidMethod + "( " + valueClass + " ) method does not exist in the " + enumClass, e);
        }
    }


}